package com.android.picotts.ui.widget;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.picotts.R;
import com.android.picotts.businiss.SpriterManager;
import com.android.picotts.businiss.model.Spriter;
import com.android.picotts.businiss.model.SpriterType;
import com.android.picotts.componet.SystemService;

public class SpirteView extends RelativeLayout implements RelativeLayout.OnClickListener{
    private static PackageManager pk;
    
    protected Spriter data;
    protected ImageView close; 
    private ImageView icon;
    private TextView text;
    
    public SpirteView(Context context) {
        this(context, null);
    }
    
    public SpirteView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(this);
        if(pk == null) {
            pk = context.getPackageManager();
        }
    }
    
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        
        icon   = (ImageView)findViewById(R.id.icon);
        text   = (TextView)findViewById(R.id.text);
        close =  (ImageView)findViewById(R.id.close);
    }
    
    public void bindData(Spriter one, boolean isEditable) {
        this.data = one;
        setEditable(isEditable);        
        if(one.type != SpriterType.APP) {
            text.setText(one.getDispalyName());
            text.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(one.getLeftDrawable()), null, null, null);
            icon.setVisibility(View.GONE);
        }else {
            text.setVisibility(View.GONE);
            try {
                icon.setImageDrawable(pk.getApplicationIcon(one.uri));
            } catch (NameNotFoundException e) {
                icon.setImageResource(R.drawable.ic_launcher);
            }
        }
    }
    
    public void setEditable(boolean isEditable) {
        close.setVisibility(isEditable ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        if(data != null) {
            if(close.getVisibility() != View.VISIBLE) {
                data.onClick(getContext());
                SystemService.getInstance().restoreFloat();
            }else {
                SpriterManager.getInstance(getContext()).remove(data);
            }
        }
    }
}